﻿using System;
using System.Collections;
using System.Text;

namespace Agile.DataAccess
{
    internal partial class DbCommand : IDbCommand
    {
        public DbCommandData Data { get; private set; }

        public DbCommand(
            DbContext dbContext,
            System.Data.IDbCommand innerCommand)
        {
            Data = new DbCommandData(dbContext, innerCommand);
            Data.ExecuteQueryHandler = new ExecuteQueryHandler(this);
        }

        public IDbCommand UseMultiResult(bool useMultipleResultset)
        {
            if (useMultipleResultset && !Data.Context.Data.FluentDataProvider.SupportsMultipleResultsets)
                throw new FluentDataException("The selected database does not support multiple resultset");

            Data.UseMultipleResultsets = useMultipleResultset;
            return this;
        }

        public IDbCommand CommandType(DbCommandTypes dbCommandType)
        {
            Data.InnerCommand.CommandType = (System.Data.CommandType)dbCommandType;
            return this;
        }

        internal void ClosePrivateConnection()
        {
            if (!Data.Context.Data.UseTransaction
                && !Data.Context.Data.UseSharedConnection)
            {
                Data.InnerCommand.Connection.Close();
                if (Data.Context.Data.OnConnectionClosed != null)
                    Data.Context.Data.OnConnectionClosed(new ConnectionEventArgs(Data.InnerCommand.Connection));
            }
        }

        public void Dispose()
        {
            if (Data.Reader != null)
                Data.Reader.Close();
            ClosePrivateConnection();
        }

        public IDbCommand Paging(int currentPage, int itemsPerPage, string orderBy)
        {
            SelectBuilderData data = new SelectBuilderData(null, null);
            data.PagingCurrentPage = currentPage < 1 ? 1 : currentPage;
            data.PagingItemsPerPage = itemsPerPage;
            data.ObjectName = this.Data.Sql.ToString();
            this.Data.Sql.Clear().Append(Data.Context.Data.FluentDataProvider.GetSqlForPagingBuilder(data, orderBy));
            return this;
        }
    }
}
